package com.ks.springcloud.controller;

import com.ks.springcloud.entity.CommonResult;
import com.ks.springcloud.entity.Payment;
import com.ks.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author：Administrator
 * @Date：2022/3/1/0001 22:11
 * @Versiion：1.0
 */
@RestController
@Slf4j
@RequestMapping("/payment")
public class PaymentController {
    @Resource
    private PaymentService paymentService;
    @Resource
    private DiscoveryClient discoveryClient;
    @Value("${server.port}")
    private String serverPort;

    @PostMapping(value = "/create")
    public CommonResult<Payment> create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        log.info("port:{} 插入结果：{}",serverPort, result);
        if(result>0){
            return new CommonResult(200,"插入成功"+serverPort);
        }else{
            return new CommonResult(400,"插入失败"+serverPort);
        }
    }


    @GetMapping("/get/{id}")
    public CommonResult getPaymenyById(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentById(id);
        log.error("port:{} 获取支付对象：{} ",serverPort, payment);
        return payment!=null?
                CommonResult.builder().code(200).data(payment).msg("查询成功！"+serverPort).build():
                CommonResult.builder().code(400).msg("未查询到相关信息！"+serverPort).build();
    }

    /**
     * 获取服务发现的服务列表信息
     * @return
     */
    @GetMapping("/getDiscoverys")
    public CommonResult getDiscoverys(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instances.forEach(item -> {
            log.info(item.getServiceId()+"\n"+item.getHost()+"\n"+item.getPort()+"\n"+item.getUri());
        });
        return CommonResult.builder().data(this.discoveryClient).build();
    }

    @GetMapping("/lb")
    public String getLb(){
        return "端口："+serverPort;
    }


    @GetMapping("/paymentOk/{time}")
    public String paymentOk(@PathVariable("time") String time){
        return "payment service "+ serverPort + "payment ok :" + time;
    }

    @GetMapping("/paymentTimeout/{time}")
    public String paymentTimeout(@PathVariable("time") String time){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "payment service "+ serverPort + "payment timeout :" + time;
    }
}
